package cn.edu.scau.cmi.zhouxinyue.spring.Controller;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;

import cn.edu.scau.cmi.zhouxinyue.hibernate.domain.dao.StudentDAO;
import cn.edu.scau.cmi.zhouxinyue.hibernate.domain.dao.TeacherDAO;
import cn.edu.scau.cmi.zhouxinyue.hibernate.domain.factory.ScauCmiHibernateSessionFactory;
import cn.edu.scau.cmi.zhouxinyue.spring.util.ApplicationContextUtil;
import cn.edu.scau.cmi.zhouxinyue.hibernate.domain.*;
import javafx.fxml.FXML;

import javafx.scene.control.Button;

import javafx.scene.control.TextField;

import javafx.scene.control.TextArea;

public class teacherController {
	@FXML
	private TextField id;
	@FXML
	private TextField name;
	@FXML
	private Button add;
	@FXML
	private TextArea show;
	@FXML
	private TextField did;
	@FXML
	private Button del;

	public void addTeacher() {
		Session session = ScauCmiHibernateSessionFactory.getSession();
		Transaction transaction = session.beginTransaction();

		String n = name.getText();
		String ii = id.getText();
		Long i = Long.parseLong(ii);
		Teacher s = new Teacher();
		s.setId(i);
		s.setName(n);

		ApplicationContext ac=ApplicationContextUtil.getApplicationContext();
		TeacherDAO SS=(TeacherDAO) ac.getBean("TeacherDAO");
		
		SS.save(s);
		transaction.commit();
		session.close();

		show.setText(null);
		TeacherDAO sdao = new TeacherDAO();
		List Student = sdao.findAll();
		Iterator<?> Ss = Student.iterator();
		while (Ss.hasNext()) {
			Teacher sc = (Teacher) Ss.next();
			String iii = Long.toString(sc.getId());
			show.appendText(sc.getName() + ' ' + iii + '\n');
		}
	}

	public void delTeacher() {
		Session session = ScauCmiHibernateSessionFactory.getSession();
		Transaction transaction = session.beginTransaction();
		String id = did.getText();
		Long ID = Long.parseLong(id);
		ApplicationContext ac=ApplicationContextUtil.getApplicationContext();
		TeacherDAO td=(TeacherDAO) ac.getBean("TeacherDAO");

		Teacher stu = td.findById(ID);
		td.delete(stu);

		transaction.commit();
		session.close();

		show.setText(null);
		TeacherDAO sdao = new TeacherDAO();
		List Student = sdao.findAll();
		Iterator<?> Ss = Student.iterator();
		while (Ss.hasNext()) {
			Teacher sc = (Teacher) Ss.next();
			String iii = Long.toString(sc.getId());
			show.appendText(sc.getName() + ' ' + iii + '\n');
		}
	}

}
